import React, { useEffect, useMemo, useState } from 'react';
import './index.less';
import Upload from './Upload/index';
import Setting from './Setting/index';
import Preview from './Preview/index';
import History from './History/index';
import { ISettings, IHistory } from './types';

let uploadData: IHistory[] = [];
export default () => {
    const [curVideo, setCurVideo] = useState<any>();
    const [settings, setSettings] = useState<ISettings>({
        x: 0,
        y: 480 - 60,
        width: 720,
        height: 60,
        maxWidth: 720,
        maxHeight: 480,
        minWidth: 100,
        minHeight: 60,
    });
    const [historys, setHistorys] = useState<IHistory[]>([]);
    const [status, setStatus] = useState('');
    const [curTime, setCurTime] = useState(0);
    const onFileChange = (info: any) => {
        console.log(info);
        setCurVideo(info.file);
    };
    /** 播放时间改变 */
    const onTimeUpdate = () => {
        if (status === 'ing') return;
        draw();
    };
    /** 绘制 */
    const draw = () => {
        const video = document.querySelector('video') as HTMLVideoElement;
        const canvas = document.getElementById('preview') as HTMLCanvasElement;
        const context = canvas.getContext('2d');
        const resultCanvas = document.getElementById('result') as HTMLCanvasElement;
        const resultContext = resultCanvas.getContext('2d');
        if (!video || !context || !resultContext) return;
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const { x, y, width, height } = settings;
        const cutImage = context.getImageData(x, y, width, height);
        resultContext.putImageData(cutImage, 0, 0);
        const base64: any = resultContext.canvas.toDataURL();
        return base64;
    };
    /** 录制状态变化后, 控制视频播放 */
    useEffect(() => {
        const video = document.querySelector('video') as HTMLVideoElement;
        if (status === 'ing') {
            video.play();
        } else {
            video.pause();
        }
    }, [status]);
    /** 录制状态变化后, 控制数据 */
    useEffect(() => {
        let timerId = setInterval(() => {
            if (status === 'ing') {
                const video = document.querySelector('video') as HTMLVideoElement;
                if (Math.abs(video.currentTime - curTime) > 1) {
                    setCurTime(Math.floor(video.currentTime));
                    const base64 = draw();
                    const result = {
                        time: curTime,
                        data: base64,
                    };
                    uploadData.push(result);
                    if (historys.length < 10) {
                        setHistorys((prev) => [...prev, result]);
                    }
                    if (uploadData.length >= 10) {
                        const json = {
                            file_dir: curVideo?.name,
                            file_data: uploadData.splice(0, 10),
                        };
                    }
                    console.log(uploadData);
                }
            }
        }, 20);
        return () => {
            clearInterval(timerId);
        };
    }, [status, curTime, historys]);
    /** 文件变化后，清除数据 */
    useEffect(() => {
        if (curVideo === undefined) return
        setCurTime(0);
        setHistorys([]);
        uploadData = [];
    }, [curVideo]);

    const uploadProps = useMemo(
        () => ({
            video: curVideo,
            onChange: onFileChange,
            onTimeUpdate,
            status,
        }),
        [curVideo, status],
    );
    const settingProps = useMemo(
        () => ({
            video: curVideo,
            settings,
            setSettings,
            status,
            setStatus,
        }),
        [curVideo, settings, status],
    );
    const previewProps = useMemo(
        () => ({
            video: curVideo,
            settings,
            setSettings,
            status,
        }),
        [curVideo, settings, status],
    );
    const historyProps = useMemo(
        () => ({
            data: historys,
            setHistorys,
        }),
        [historys],
    );
    return (
        <div className="home">
            <Upload {...uploadProps} />
            <Setting {...settingProps} />
            <Preview {...previewProps} />
            <History {...historyProps} />
        </div>
    );
};
